package com.ruoyi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 节点状态枚举
enum NodeStatus {
    INITIALIZED("初始化"),
    SUCCESS("成功"),
    FAILED("失败");

    private final String displayName;

    NodeStatus(String displayName) {
        this.displayName = displayName;
    }

    public String getDisplayName() {
        return displayName;
    }
}

// 节点类型枚举
enum NodeType {
    PHASE("阶段"),
    CATEGORY("校验分类"),
    OBJECT("校验对象");

    private final String displayName;

    NodeType(String displayName) {
        this.displayName = displayName;
    }

    public String getDisplayName() {
        return displayName;
    }
}

// 日志类
class Log {
    private final String id;
    private final String content;

    public Log(String id, String content) {
        this.id = id;
        this.content = content;
    }

    public String getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

// 树节点类
class TreeNode {
    // 节点ID
    private final String id;
    // 节点名称
    private final String name;
    // 节点类型
    private final NodeType type;
    // 父节点ID
    private final String parentId;
    // 使能状态(是否显示)
    private boolean enabled;
    //节点状态
    private NodeStatus status;
    // 子节点
    private final List<TreeNode> children;
    // 使能日志ID
    private String enableLogId;
    // 节点状态日志ID
    private String statusLogId;

    public TreeNode(String id, String name, NodeType type, String parentId) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.parentId = parentId;
        this.enabled = false;
        this.status = NodeStatus.INITIALIZED;
        this.children = new ArrayList<>();
    }

    // Getters and Setters
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public NodeType getType() {
        return type;
    }

    public String getParentId() {
        return parentId;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public NodeStatus getStatus() {
        return status;
    }

    public void setStatus(NodeStatus status) {
        this.status = status;
    }

    public List<TreeNode> getChildren() {
        return children;
    }

    public String getEnableLogId() {
        return enableLogId;
    }

    public void setEnableLogId(String enableLogId) {
        this.enableLogId = enableLogId;
    }

    public String getStatusLogId() {
        return statusLogId;
    }

    public void setStatusLogId(String statusLogId) {
        this.statusLogId = statusLogId;
    }
}

// 环境校验主类
public class EnvironmentValidator {

    /**
     * 执行环境校验
     * @param logs 实时日志列表
     * @param initialNodes 初始节点配置
     * @return 更新后的根节点
     */
    public TreeNode validateEnvironment(List<Log> logs, List<TreeNode> initialNodes) {
        // 1. 构建树
        Map<String, TreeNode> nodeMap = buildTree(initialNodes);
        
        // 2. 处理日志更新
        processLogUpdates(logs, nodeMap);
        
        // 3. 从下往上更新父节点状态和使能
        TreeNode root = findRootNode(nodeMap);
        if (root != null) {
            updateParentNodesStatus(root);
            updateParentNodesEnable(root);
        }
        
        return root;
    }

    // 构建树结构
    private Map<String, TreeNode> buildTree(List<TreeNode> initialNodes) {
        Map<String, TreeNode> nodeMap = new HashMap<>();
        
        // 创建所有节点并建立映射
        for (TreeNode node : initialNodes) {
            nodeMap.put(node.getId(), node);
        }
        
        // 建立父子关系,如果存在父节点，且父节点存在，则将当前节点添加到父节点的子节点列表中
        for (TreeNode node : nodeMap.values()) {
            if (node.getParentId() != null && nodeMap.containsKey(node.getParentId())) {
                nodeMap.get(node.getParentId()).getChildren().add(node);
            }
        }
        
        return nodeMap;
    }

    // 处理日志更新
    private void processLogUpdates(List<Log> logs, Map<String, TreeNode> nodeMap) {
        //遍历日志,获取对应的节点的使能状态日志ID和节点状态日志ID,更新节点使能状态和状态
        for (Log log : logs) {
            for (TreeNode node : nodeMap.values()) {
                // 更新使能状态
                if (log.getId().equals(node.getEnableLogId())) {
                    node.setEnabled(parseEnableStatus(log.getContent()));
                }
                
                // 更新节点状态
                if (log.getId().equals(node.getStatusLogId())) {
                    node.setStatus(parseNodeStatus(log.getContent()));
                }
            }
        }
    }

    // 解析使能状态
    private boolean parseEnableStatus(String logContent) {
        // 实际实现应根据日志格式解析
        return "true".equalsIgnoreCase(logContent) || "1".equals(logContent);
    }

    // 解析节点状态
    private NodeStatus parseNodeStatus(String logContent) {
        // 实际实现应根据日志格式解析
        if ("success".equalsIgnoreCase(logContent)) {
            return NodeStatus.SUCCESS;
        } else if ("failed".equalsIgnoreCase(logContent)) {
            return NodeStatus.FAILED;
        }
        return NodeStatus.INITIALIZED;
    }

    // 获取根节点
    private TreeNode findRootNode(Map<String, TreeNode> nodeMap) {
        //遍历节点，找到类型为PHASE并且父节点为null的节点,就是根节点
        for (TreeNode node : nodeMap.values()) {
            if (node.getType() == NodeType.PHASE && node.getParentId() == null) {
                return node;
            }
        }
        return null;
    }

    // 递归更新父节点状态
    private void updateParentNodesStatus(TreeNode node) {
        // 如果节点为空则返回
        if (node == null) {return;}
        
        // 处理子节点,更新子节点状态
        for (TreeNode child : node.getChildren()) {
            updateParentNodesStatus(child);
        }
        
        // 如果是叶子节点则不需要处理状态
        if (node.getChildren().isEmpty()) {return;}
        
        // 根据节点类型处理状态
        switch (node.getType()) {
            case CATEGORY:
                updateCategoryStatus(node);
                break;
            case PHASE:
                updatePhaseStatus(node);
                break;
            case OBJECT:
                // 校验对象不需要处理,因为是叶子节点
                break;
        }
    }

    // 更新分类节点状态
    private void updateCategoryStatus(TreeNode category) {
        //定义状态变量
        boolean allSuccess = true;
        boolean anyFailed = false;
        boolean anyInitialized = false;

        //遍历子节点,判断子节点状态
        for (TreeNode child : category.getChildren()) {
            if (child.getStatus() == NodeStatus.FAILED) {
                anyFailed = true;
            }
            if (child.getStatus() == NodeStatus.INITIALIZED) {
                anyInitialized = true;
            }
            if (child.getStatus() != NodeStatus.SUCCESS) {
                allSuccess = false;
            }
        }

        // 更新分类节点状态
        if (anyFailed) {
            category.setStatus(NodeStatus.FAILED);
        } else if (allSuccess) {
            category.setStatus(NodeStatus.SUCCESS);
        } else if (anyInitialized) {
            category.setStatus(NodeStatus.INITIALIZED);
        }
    }

    // 更新阶段节点状态
    private void updatePhaseStatus(TreeNode phase) {
        //定义状态变量
        boolean allSuccess = true;
        boolean anyFailed = false;
        boolean anyInitialized = false;

        //遍历子节点,判断子节点状态
        for (TreeNode child : phase.getChildren()) {
            if (child.getStatus() == NodeStatus.FAILED) {
                anyFailed = true;
            }
            if (child.getStatus() == NodeStatus.INITIALIZED) {
                anyInitialized = true;
            }
            if (child.getStatus() != NodeStatus.SUCCESS) {
                allSuccess = false;
            }
        }

        // 更新阶段节点状态
        if (anyFailed) {
            phase.setStatus(NodeStatus.FAILED);
        } else if (allSuccess) {
            phase.setStatus(NodeStatus.SUCCESS);
        } else if (anyInitialized) {
            phase.setStatus(NodeStatus.INITIALIZED);
        }
    }

    // 递归更新父节点使能状态
    private void updateParentNodesEnable(TreeNode node) {
        //如果节点为空则返回
        if (node == null) {return;}
        
        // 先处理子节点
        for (TreeNode child : node.getChildren()) {
            updateParentNodesEnable(child);
        }
        
        // 叶子节点不需要处理使能状态
        if (node.getChildren().isEmpty()) {return;}
        
        // 分类节点的使能状态由子节点决定
        if (node.getType() == NodeType.CATEGORY) {
            boolean anyChildEnabled = false;
            for (TreeNode child : node.getChildren()) {
                if (child.isEnabled()) {
                    anyChildEnabled = true;
                    break;
                }
            }
            node.setEnabled(anyChildEnabled);
        }
        // 阶段节点的使能状态不会根据子节点修改
    }
}